﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ThuVien;
using System.Data;
using System.Web.Services;
using System.Web.Script.Services;
namespace TranTekBE.KPI_NhanSu
{
    public partial class Lich_Lam_Viec_Nhan_Vien : PageRequireLogin
    {

        public string JsonStringSchedule = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            //Load JS
            ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "LoadJS", "LoadJS();", true);
            //
            if (UserInfo.MemberKPI != true)
            {
                
                if (!IsPostBack)
                {
                    if (Request.QueryString["store"] != null || Request.QueryString["user"] != null || Request.QueryString["starttime"] != null || Request.QueryString["endtime"] != null)
                    {
                        LoadSchedule(Request.QueryString["store"], Request.QueryString["user"], Request.QueryString["starttime"], Request.QueryString["endtime"]);
                    }
                    else
                    {
                        LoadSchedule(UserInfo.Stores, "", "", "");
                    }
                    // Get user
                    FunctionsUtils.GetDropListUser(droplist_ten_nhan_vien_loc_kq);
                    droplist_ten_nhan_vien_loc_kq.SelectedValue = Request.QueryString["user"];
                    //
                    FunctionsUtils.GetDropListStore(droplist_cua_hang_loc_kq);
                    droplist_cua_hang_loc_kq.SelectedValue = Request.QueryString["store"];
                    txt_StartTime.Text = Request.QueryString["starttime"];
                    txt_EndTime.Text = Request.QueryString["endtime"];
                }
            }
            else
            {
                Response.Redirect("../Admin/DontPermission.aspx");
            }
        }


        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static List<string> UpdateCalendar(string value, string date, string idlich)
        {
            List<string> abc = new List<string>();
            User objUser = new User();
            objUser = HttpContext.Current.Session["UserInfo"] as User;
            // Cut space
            string trim_value = value.Replace(" ", "");
            //

            //
            string[] separators = { "-", ":" };
            string get_value = trim_value;
            string[] words = get_value.Split(separators, StringSplitOptions.RemoveEmptyEntries);

            string get_ca_user = words[1];
            string get_store_user = words[2];
            string get_name_user = words[3];
            string get_id_user_update = words[4] + "-" + words[5];



            string sql_update_user_schedule = @" UPDATE tbl_LichLamViec
                        SET
                        
                        NGAY_THEM_VAO = '" + date + @"',
                        NGUOI_THEM_VAO = '" + objUser.UserName + @"'
                        WHERE ID_LICH_LAM_VIEC='" + idlich + @"'
                        ";
            int check_exist_event = CheckDataExist(get_id_user_update, get_ca_user, date);
            if (check_exist_event == 1)
            {
                FunctionsUtils.Database2.ExecuteNonQuery(sql_update_user_schedule);
            }

            abc.Add(check_exist_event.ToString());
            return abc;
        }
        [WebMethod]
        // [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string DelEvent(string idevent)
        {
            List<string> listevent = new List<string>();
            string sql_del_event_schedule = @" DELETE FROM tbl_LichLamViec
            WHERE ID_LICH_LAM_VIEC = '" + idevent + @"'
                        ";
            string sql_check_date_del = "SELECT *  FROM tbl_LichLamViec WHERE ID_LICH_LAM_VIEC = '" + idevent + "'";
            DataSet ds_check_date_del = FunctionsUtils.Database2.ExecuteQuery(sql_check_date_del);
            DateTime get_ngay_event = Convert.ToDateTime(ds_check_date_del.Tables[0].Rows[0]["NGAY_THEM_VAO"].ToString());
            if (get_ngay_event >= DateTime.Now)
            {
                FunctionsUtils.Database2.ExecuteNonQuery(sql_del_event_schedule);
                return "Ok";
            }

            return "";
        }


        public void LoadSchedule(string getstore, string getuser, string timestart, string timeend)
        {
            DateTime get_date_now = DateTime.Now;
            // Lấy ngày hôm nay (m.d.y)
            string str_get_date_now = get_date_now.ToShortDateString();
            // Lấy tháng (m) & năm (y)
            string str_get_month = get_date_now.Month.ToString();
            string str_get_year = get_date_now.Year.ToString();
            // Lấy biến ngày (d)
            string str_day_now = get_date_now.Day.ToString();
            //
            DateTime dtime = new DateTime(Convert.ToInt32(str_get_year), Convert.ToInt32(str_get_month), 1);
            dtime = dtime.AddMonths(1).AddDays(-1);//
            string get_end_day_of_month = dtime.Day.ToString();
            // End get day
            //
            string sql_schedule_user = @"SELECT * 
            FROM tbl_LichLamViec 
            WHERE 1=1 
            ";
            if (getstore != "")
            {
                sql_schedule_user += " AND CUA_HANG_DANG_LAM_VIEC = '" + getstore + "'";
            }
            //else
            //{
            //    sql_schedule_user += " AND CUA_HANG_DANG_LAM_VIEC = '" + UserInfo.Stores + "'";
            //}

            if (getuser != "")
            {
                sql_schedule_user += " AND ID_USER = '" + getuser + "'";
            }
            if (timestart != "" && timeend != "")
            {
                sql_schedule_user += @"and NGAY_THEM_VAO >= '" + timestart + @"  00:00:00.000' 
                                       and NGAY_THEM_VAO < = '" + timeend + @"  00:00:00.000' 
                                       order by NGAY_THEM_VAO asc";
            }
            else
            {
                if (timestart == "" && timeend != "")
                {
                    sql_schedule_user += "and NGAY_THEM_VAO = '" + timeend + "'";
                }
                else
                    if (timeend == "" && timestart != "")
                    {
                        sql_schedule_user += "and NGAY_THEM_VAO = '" + timestart + "'";
                    }
                    else
                    {
                        sql_schedule_user += @"and NGAY_THEM_VAO >= '" + str_get_month + @"/1/" + str_get_year + @"  00:00:00.000' 
                                       and NGAY_THEM_VAO < = '" + DateTime.Now.AddMonths(2).AddDays(-1).ToShortDateString() + @"  23:59:59.999' 
                                       order by NGAY_THEM_VAO asc";
                    }
            }
            DataSet ds_schedule_user = FunctionsUtils.Database2.ExecuteQuery(sql_schedule_user);
            JsonStringSchedule = " ";
            foreach (DataRow row in ds_schedule_user.Tables[0].Rows)
            {
                string ID_Lich = row[0].ToString();
                string get_id_user = row["ID_USER"].ToString();
                string user_info = row["NAME_USER"].ToString();
                string cua_hang = row["CUA_HANG_DANG_LAM_VIEC"].ToString();
                string ca_lam = row["CA_LAM_VIEC"].ToString();
                string thoi_gian = row["NGAY_THEM_VAO"].ToString();
                JsonStringSchedule += "{title:'Ca:" + ca_lam + "-" + cua_hang + "-" + user_info + "-" + get_id_user + "',start:'" + thoi_gian + "',id:'" + ID_Lich + "'},";
            }

            JsonStringSchedule = JsonStringSchedule.Substring(0, JsonStringSchedule.Length - 1);
        }
        protected void droplist_ten_nhan_vien_loc_kq_SelectedIndexChanged(object sender, EventArgs e)
        {
            Response.Redirect("Lich-Lam-Viec-Nhan-Vien.aspx?store=" + droplist_cua_hang_loc_kq.SelectedValue.ToString() + "&user=" + droplist_ten_nhan_vien_loc_kq.SelectedValue.ToString() + "&starttime=" + txt_StartTime.Text + "&endtime=" + txt_EndTime.Text);
        }
        protected void droplist_cua_hang_loc_kq_SelectedIndexChanged(object sender, EventArgs e)
        {
            Response.Redirect("Lich-Lam-Viec-Nhan-Vien.aspx?store=" + droplist_cua_hang_loc_kq.SelectedValue.ToString() + "&user=" + droplist_ten_nhan_vien_loc_kq.SelectedValue.ToString() + "&starttime=" + txt_StartTime.Text + "&endtime=" + txt_EndTime.Text);
        }

        public static int CheckDataExist(string idusername, string ca, string day)
        {
            DataSet ds_store = FunctionsUtils.Database.ExecuteQuery("select C007000 as IDCuaHang ,C007001 as CuaHang from T0070  where C007001 not in ('RACHMIEU','PMT')");
            string str_sosanh_store = "CUA_HANG_DANG_LAM_VIEC in ( ";
            for (int i = 0; i < ds_store.Tables[0].Rows.Count; i++)
            {
                str_sosanh_store += "'" + ds_store.Tables[0].Rows[i]["CuaHang"].ToString() + "',";
            }
            str_sosanh_store = str_sosanh_store.TrimEnd(',');
            str_sosanh_store = str_sosanh_store + ")";

            string sql_so_sanh = @"select * from  tbl_LichLamViec 
                  where ID_USER = '" + idusername + @"' and " + str_sosanh_store + @"
                  and  CA_LAM_VIEC = " + ca + @"
                  and NGAY_THEM_VAO = '" + day + @"'";

            DataSet ds = FunctionsUtils.Database2.ExecuteQuery(sql_so_sanh);
            if (FunctionsUtils.isDataSetNullOrEmpty(ds) == true)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }

        protected void txt_StartTime_TextChanged(object sender, EventArgs e)
        {
            Response.Redirect("Lich-Lam-Viec-Nhan-Vien.aspx?store=" + droplist_cua_hang_loc_kq.SelectedValue.ToString() + "&user=" + droplist_ten_nhan_vien_loc_kq.SelectedValue.ToString() + "&starttime=" + txt_StartTime.Text + "&endtime=" + txt_EndTime.Text);
        }

        protected void txt_EndTime_TextChanged(object sender, EventArgs e)
        {
            Response.Redirect("Lich-Lam-Viec-Nhan-Vien.aspx?store=" + droplist_cua_hang_loc_kq.SelectedValue.ToString() + "&user=" + droplist_ten_nhan_vien_loc_kq.SelectedValue.ToString() + "&starttime=" + txt_StartTime.Text + "&endtime=" + txt_EndTime.Text);
        }

    }
}